package com.fcai.microserv.jwt.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fcai.microserv.jwt.FcaiSecurityChecker;
import com.fcai.microserv.model.ServiceRespModel;
import com.fcai.microserv.model.ServiceResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletResponse;

public abstract class AbstractFcaiSecurityInterceptor extends HandlerInterceptorAdapter {

    protected ObjectMapper jsonMapper = new ObjectMapper();

    protected void responseError(HttpServletResponse response, ServiceRespModel code) throws Exception {
        ServiceResult<Void> result = ServiceResult.result(code);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(jsonMapper.writeValueAsString(result));
    }

    protected FcaiSecurityChecker findSecurityCheckAnnotation(HandlerMethod handlerMethod) {
        // 1、方法级别注解优先级最高
        FcaiSecurityChecker securityChecker = handlerMethod.getMethod().getAnnotation(FcaiSecurityChecker.class);
        if (securityChecker != null) {
            return securityChecker;
        }

        // 2、类级别
        securityChecker = handlerMethod.getBeanType().getAnnotation(FcaiSecurityChecker.class);
        return securityChecker;
    }

}
